package org.gbif.agi.webapp.action;

import com.opensymphony.xwork2.Preparable;
import org.appfuse.service.GenericManager;
import org.gbif.agi.model.RelationshipType;
import org.appfuse.webapp.action.BaseAction;

import java.util.List;

public class RelationshipTypeAction extends BaseAction implements Preparable {
    private GenericManager<RelationshipType, Long> relationshipTypeManager;
    private List relationshipTypes;
    private RelationshipType relationshipType;
    private Long  id;

    public void setRelationshipTypeManager(GenericManager<RelationshipType, Long> relationshipTypeManager) {
        this.relationshipTypeManager = relationshipTypeManager;
    }

    public List getRelationshipTypes() {
        return relationshipTypes;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String relationshipTypeId = getRequest().getParameter("relationshipType.id");
            if (relationshipTypeId != null && !relationshipTypeId.equals("")) {
                relationshipType = relationshipTypeManager.get(new Long(relationshipTypeId));
            }
        }
    }

    public String list() {
        relationshipTypes = relationshipTypeManager.getAll();
        return SUCCESS;
    }

    public void setId(Long  id) {
        this. id =  id;
    }

    public RelationshipType getRelationshipType() {
        return relationshipType;
    }

    public void setRelationshipType(RelationshipType relationshipType) {
        this.relationshipType = relationshipType;
    }

    public String delete() {
        relationshipTypeManager.remove(relationshipType.getId());
        saveMessage(getText("relationshipType.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            relationshipType = relationshipTypeManager.get(id);
        } else {
            relationshipType = new RelationshipType();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (relationshipType.getId() == null);

        relationshipTypeManager.save(relationshipType);

        String key = (isNew) ? "relationshipType.added" : "relationshipType.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}